package com.aynu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.aynu.common.exception.NoStockException;
import com.aynu.common.to.mq.OrderTo;
import com.aynu.common.utils.R;
import com.aynu.common.vo.MemberRespVo;
import com.aynu.gulimall.order.constant.OrderConstant;
import com.aynu.gulimall.order.dao.OrderItemDao;
import com.aynu.gulimall.order.entity.OrderItemEntity;
import com.aynu.gulimall.order.entity.PaymentInfoEntity;
import com.aynu.gulimall.order.enume.OrderStatusEnum;
import com.aynu.gulimall.order.feign.CartFeignService;
import com.aynu.gulimall.order.feign.MemberFeignService;
import com.aynu.gulimall.order.feign.ProductFeignService;
import com.aynu.gulimall.order.feign.WareFeignService;
import com.aynu.gulimall.order.iterceptor.LoginInterceptor;
import com.aynu.gulimall.order.service.OrderItemService;
import com.aynu.gulimall.order.service.PaymentInfoService;
import com.aynu.gulimall.order.to.OrderCreateTo;
import com.aynu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import feign.RequestInterceptor;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.order.dao.OrderDao;
import com.aynu.gulimall.order.entity.OrderEntity;
import com.aynu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private WareFeignService wareFeignService;
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("order_sn",key).or().eq("member_id",key);
        }
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //获取登陆用户的信息
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();

        //线程之间共享RequestAttributes的数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> adddress = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            log.info("远程查询会员的收货地址列表");
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setMemberAddressVoList(address);
        }, executor);


        log.info("远程查询购物车的信息");
        CompletableFuture<Void> cartItem = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItemVos = cartFeignService.getCurrentUserCartItem();
            orderConfirmVo.setOrderItemVoList(orderItemVos);
            //feign在远程调用之前要构造请求，调用很多的拦截器【RequestInterceptor】
            //解决方案：加上feign的请求拦截器，进行功能增强
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> orderItemVoList = orderConfirmVo.getOrderItemVoList();
            List<Long> collect = orderItemVoList.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            log.info("调用远程服务查库存");
            R skuHasStock = wareFeignService.getSkuHasStock(collect);
            List<SkuHasStockVo> hasStockVos = skuHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {});
            if (!CollectionUtils.isEmpty(hasStockVos)) {
                Map<Long, Boolean> map = hasStockVos.stream().collect(Collectors.
                        toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        });

        log.info("查询用户级分");
        orderConfirmVo.setIntegration(memberRespVo.getIntegration());

        //其他数据动态计算

        //TODO 防重令牌
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX,token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        //等待线程执行完成
        try {
            CompletableFuture.allOf(adddress,cartItem).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        return orderConfirmVo;
    }

    //同一个对象内事务方法互调默认失效，原因：绕过了代理对象
    //事务对象使用代理对象来控制
    @Transactional
    public void c(){
        //这种设置在b，c方法上的事务注解是无效的，
//        a();
//        b();
        //使用代理对象调用本类方法
//        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
//        orderService.a();
//        orderService.b();

        //如果是不同的service则是有效的
//        bservice.a();
//        cservice.b();
    }

    @Transactional
    public void a(){

    }

    @Transactional
    public void b(){

    }


    //本地事务，在分布式系统中，只能控制 自己的回滚，控制不了其他服务的回滚
    //分布式事务，最大的原因，网络问题+分布式机器
    //isolation = Isolation.READ_COMMITTED：隔离级别
    //propagation = Propagation.REQUIRED（在一个方法中，如果有一个事务则公用一个事务）,Propagation.REQUIRES_NEW（在一个方法中，如果有一个事务则不公用一个事务）：传播行为
//    @GlobalTransactional（Seata需要加一系列的锁，不利用高并发）
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        submitVoThreadLocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        //下单，去创建订单，验证令牌，验证价格，锁定库存。。

        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        responseVo.setCode(0);
        //获取登陆用户的信息
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();
        //1、验证令牌
        //原子验证令牌和删除令牌【1:成功，0：失败】
        Long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX), orderToken);
        if(result==0L){
            responseVo.setCode(1);
            return responseVo;
        }else {
            //令牌验证成功
            //创建订单
            OrderCreateTo order = createOrderTo();

            //2、验证价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();

            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比
                //TODO 3、保存订单
                saveOrder(order);

                //4、库存锁定,只要有异常，回滚订单数据
                //订单号、所有订单项信息(skuId,skuNum,skuName)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                //获取出要锁定的商品数据信息
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);

                //TODO 调用远程锁定库存的方法
                //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
                //为了保证高并发，不推荐使用seata，因为是加锁，串行化，提升不了效率,可以发消息给库存服务
                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁定成功
                    responseVo.setOrder(order.getOrder());

                    //TODO 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());

                    //删除购物车里的数据
//                    redisTemplate.delete(CART_PREFIX+memberResponseVo.getId());
//                    int nu = 10 / 0;
                    return responseVo;
                } else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
//                     responseVo.setCode(3);
//                     return responseVo;
                }

            } else {
                responseVo.setCode(2);
                return responseVo;
            }

        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
    }

    /**
     * 关单操作
     * @param orderEntity
     */
    @Override
    @Transactional
    public void closeOrder(OrderEntity orderEntity) {
        //查询订单最新状态
        OrderEntity currentOrderEntity = this.getById(orderEntity.getId());
        //判断订单状态是否是已付款
        if (currentOrderEntity != null &&
                currentOrderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //设置参数
            OrderEntity updateOrderEntity = new OrderEntity();
            updateOrderEntity.setId(currentOrderEntity.getId());
            updateOrderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            log.info("订单号：{},超过30分钟未付款，进行关单操作",currentOrderEntity.getOrderSn());
            this.updateById(updateOrderEntity);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);

            //考虑到如果存在机器卡顿，解锁库存的消息比关单的消息先到达，则需要在关单后，再次发送消息进行解锁库存操作
            try {
                //保证信息一定会发送除去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                //定期扫描数据库将失败的消息再次发送
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.#",orderTo);
            } catch (AmqpException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询订单信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderEntity = this.getOrderByOrderSn(orderSn);
        OrderItemEntity orderItemEntity = orderItemService.list(
                new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn)).get(0);


        BigDecimal bigDecimal = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject("谷粒商城收银-"+orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());

        return payVo;
    }

    /**
     * 查询用户的订单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils listWithItem(Map<String, Object> params) {

        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId())
                        .orderByDesc("create_time"));

        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntityList = orderItemService.list(
                    new QueryWrapper<OrderItemEntity>().
                            eq("order_sn", order.getOrderSn()));
            order.setItemEntityList(orderItemEntityList);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);

        return new PageUtils(page);
    }

    /**
     * 修改订单状态为已支付
     * @param payAsyncVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String handPayResult(PayAsyncVo payAsyncVo) {
        //1、保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        //支付宝流水号
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        //订单号
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        //支付状态
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        //回调时间
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        //2、修改订单状态变为已支付
        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS")
                || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")){
            String orderSn = payAsyncVo.getOut_trade_no();
            baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 保存订单数据到数据库
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    public OrderCreateTo createOrderTo(){
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成订单
        OrderEntity orderEntity = createOrder(orderSubmitVo);
        orderCreateTo.setOrder(orderEntity);

        //2、获取所有所有的订单项信息
        List<OrderItemEntity> orderItemEntityList = buildOrderItems(orderEntity.getOrderSn());
        orderCreateTo.setOrderItems(orderItemEntityList);

        //3、计算价格相关
        computePrice(orderEntity,orderItemEntityList);

        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntityList) {
        BigDecimal total = new BigDecimal("0.0");

        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity orderItemEntity : orderItemEntityList) {
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());

            BigDecimal realAmount = orderItemEntity.getRealAmount();
            total = total.add(realAmount);

            gift = gift.add(new BigDecimal(orderItemEntity.getGiftIntegration()));
            growth = growth.add(new BigDecimal(orderItemEntity.getGiftGrowth()));
        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //各种优惠总金额
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);

        //设置积分
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 创建订单
     * @param orderSubmitVo
     * @return
     */
    private OrderEntity createOrder(OrderSubmitVo orderSubmitVo) {
        MemberRespVo memberRespVo = LoginInterceptor.loginUser.get();
        //生成订单号
        String timeId = IdWorker.getTimeId();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(timeId);
        orderEntity.setMemberId(memberRespVo.getId());
        //获取收货地址
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo data = fare.getData(new TypeReference<FareVo>() {});

        //设置运费信息
        orderEntity.setFreightAmount(data.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(data.getAddress().getCity());
        orderEntity.setReceiverName(data.getAddress().getName());
        orderEntity.setReceiverPhone(data.getAddress().getPhone());
        orderEntity.setReceiverPostCode(data.getAddress().getPostCode());
        orderEntity.setReceiverProvince(data.getAddress().getProvince());
        orderEntity.setReceiverRegion(data.getAddress().getRegion());

        //设置订单状态相关
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);

        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取确定每一个购物项的价格
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        List<OrderItemEntity> orderItemEntities = null;
        if (!CollectionUtils.isEmpty(currentUserCartItem)){
            //创建每一个订单项信息
            orderItemEntities = currentUserCartItem.stream().map((cartItem)->{
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return orderItemEntities;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //查询spu信息
        Long skuId = cartItem.getSkuId();
        R spuInfoR = productFeignService.getSpuInfoBuSkuId(skuId);
        SpuInfoVo spuInfoRData = spuInfoR.getData(new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuId(spuInfoRData.getId());
        orderItemEntity.setSpuBrand(spuInfoRData.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoRData.getSpuName());
        orderItemEntity.setCategoryId(spuInfoRData.getCatalogId());

        //商品sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());

        //积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString())).intValue());

        //订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice()
                .multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //剪掉优惠的金额
        BigDecimal newPrice = origin.subtract(orderItemEntity.getPromotionAmount()).
                subtract(orderItemEntity.getCouponAmount()).
                subtract(orderItemEntity.getIntegrationAmount());
        //实际价格
        orderItemEntity.setRealAmount(newPrice);

        return orderItemEntity;
    }
}